package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"os"
	"strings"
	"time"
)

type Clock struct {
	name string
	host string
	time string
}

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, "用法: clockwall NAME=HOST:PORT [NAME2=HOST2:PORT2...]\n")
		os.Exit(1)
	}

	//创建时钟列表
	clocks := make([]*Clock, 0)
	for _, arg := range os.Args[1:] {
		parts := strings.Split(arg, "=")
		if len(parts) != 2 {
			fmt.Fprintf(os.Stderr, "参数格式错误: %s\n", arg)
			os.Exit(1)
		}
		//创建始终对象， 然后补充始终对象的参数。
		clocks = append(clocks, &Clock{name: parts[0], host: parts[1]})
	}

	//将clock连接到所有始终服务器
	for _, clock := range clocks {
		go connectToClock(clock)
	}

	//定期显示所有时钟
	for {
		fmt.Printf("\033[2J")
		fmt.Printf("\033[H")

		for _, clock := range clocks {
			fmt.Printf("%-15s", clock.name)
		}
		fmt.Println()
		for _, clock := range clocks {
			fmt.Printf("%-15s", clock.time)
		}
		fmt.Println()

		time.Sleep(100 * time.Millisecond)
	}
}

func connectToClock(clock *Clock) {
	conn, err := net.Dial("tcp", clock.host)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	scanner := bufio.NewScanner(conn)
	for scanner.Scan() {
		clock.time = scanner.Text()
	}
}
